<template>
  <div class="table-box">
    <ProTable ref="proTable" title="设备列表" :columns="columns" :data="equipmentList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDrawerStatic('新增')">新增设备</el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawerStatic('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawerStatic('编辑', scope.row)">编辑</el-button>
        <!-- <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button> -->
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <EquipmentDrawer ref="drawerRef" @refresh="refreshTable" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, onMounted } from "vue";
import { Equipment } from "@/api/interface";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import EquipmentDrawer from "@/views/proTable/components/EquipmentDrawer.vue";
import axios from "axios";
import { ElMessageBox, ElMessage } from "element-plus";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 表格配置项
const columns: ColumnProps<Equipment.ResEquipment>[] = [
  { type: "selection", fixed: "left", width: 80 },
  {
    prop: "equipmentName",
    label: "设备名称",
    search: { el: "input" }
  },
  {
    prop: "ratedPower",
    label: "额定功率",
    search: { el: "input" }
  },
  {
    prop: "functionDescription",
    label: "功能描述",
    width: 200
  },
  {
    prop: "safetyInstructions",
    label: "操作文本",
    width: 200
  },
  {
    prop: "createTime",
    label: "创建时间",
    width: 180,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" },
      defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 300 }
];

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof EquipmentDrawer> | null>(null);

// 静态方法（操作静态数组）
const openDrawerStatic = (title: string, row: Partial<Equipment.ResEquipment> = {}) => {
  // 定义静态操作
  const params = {
    title,
    isView: title === "查看",
    row: { ...row } // 静态模式下仅操作此行数据
  };
  drawerRef.value?.acceptParams(params);
};
const equipmentList = ref();
const baseUrl = import.meta.env.VITE_BASE_URL;

const initFormData = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const userId = Number(userInfo.id) || 0; // 如果没有 id，则使用默认值 0
    //数据库
    const response = await axios.post(baseUrl + "/api/carbon/getAllEquipments", {
      userId: userId
    });
    console.log("响应数据_读取设备列表:", response.data);
    if (response.data && response.data.code === 200) {
      equipmentList.value = response.data.data;
      console.log("设备列表:", equipmentList.value);
    } else {
      // 处理后端返回的错误信息
      const errorMsg = response.data.msg || "获取设备列表失败";
      console.error("获取设备列表错误:", errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("获取设备列表出错:", error);
    ElMessage.error("获取设备列表失败，可能是因为参数错误或网络问题");
  }
};

const deleteAccount = async (params: Equipment.ResEquipment) => {
  ElMessageBox.confirm("是否删除该项?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning", // 使用字符串形式的类型
    draggable: true
  })
    .then(async () => {
      try {
        const response = await axios.post(baseUrl + "/api/carbon/deleteEquipment", {
          id: params.id
        });
        if (response.data && response.data.code === 200) {
          ElMessage({
            type: "success",
            message: "删除设备成功!"
          });
          await initFormData(); // 删除成功后刷新列表
        } else {
          ElMessage.error(response.data.msg || "删除失败");
        }
      } catch (error) {
        console.error("删除设备出错:", error);
        ElMessage.error("删除设备失败，可能是因为参数错误或网络问题");
      }
    })
    .catch(() => {
      // 如果用户取消了操作，则不做任何处理
    });
};

onMounted(() => {
  initFormData();
});

const refreshTable = async () => {
  await initFormData();
};
</script>
